package com.shuigu.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.shuigu.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mp通用字段自动赋值
 */
@Component
@Slf4j
public class CommonFieldHandler implements MetaObjectHandler {

    // 需要使用 MyBatis-Plus 提供的插入方法（如 insert）进行插入操作。
    @Override
    public void insertFill(MetaObject metaObject) {
        try{
            // Long currentId = DaoCaoSecurityUtil.getLoginUser().getId();
            String username = SecurityUtils.getLoginUser().getUsername();
            if(username != null && !"".equals(username)){
                this.strictInsertFill(metaObject, "createUser", String.class, username);
                this.strictInsertFill(metaObject, "updateUser", String.class, username);
                this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
                this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            }else {
                log.warn("新增时未找到相关信息");
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    // 需要使用 MyBatis-Plus 提供的更新方法（如 updateById、update）进行更新操作。lambdaUpdate不生效。
    @Override
    public void updateFill(MetaObject metaObject) {
        try{
            // Long currentId = DaoCaoSecurityUtil.getLoginUser().getId();
            String username = SecurityUtils.getLoginUser().getUsername();
            if(username != null && !"".equals(username)){
                this.strictUpdateFill(metaObject, "updateUser", String.class, username);
                this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            }else {
                log.warn("更新时未找到相关信息");
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }
}
